<template>
    <div class="e-form">
        <BillTop  @cancel="handleClose"></BillTop>
        <div class="tabs">
            <el-tabs
                tab-position="left"
                v-model="tabsName"
                @tab-click="onChangeTab"
            >
                <el-tab-pane
                    label="基本信息"
                    name="baseInfo"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="物资明细"
                    name="detailed"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="附件信息"
                    name="attach"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="审核历史"
                    name="auditHistory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>

                <div>
                    <div id="baseInfoCon" class="con">
                        <div class="tabs-title" id="baseInfo">基本信息</div>
                        <div style="width: 100%" class="form">
                            <el-form
                                :model="basicForm"
                                :label-width="formLabelWidth"
                                ref="ruleForm"
                                :rules="rules"
                                class="demo-ruleForm"
                            >
                             <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="计划编号：">
                                            <span>{{ basicForm.annualDemandPlanBillNo }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="变更编号：">
                                            <span>{{ basicForm.billNo }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="单据机构：">
                                            <span>{{ basicForm.orgName }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="采购方式：">
                                            <span>{{
                                                basicForm.purchaseType == 0
                                                    ? '普通采购'
                                                    : '集中采购'
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item
                                            label="变更日期："
                                            prop="planDate"
                                        >
                                            <span>
                                                {{ basicForm.planDate }}
                                            </span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>

                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item
                                            label="不含税计划金额（元）："
                                        >
                                            <span>
                                                {{
                                                    basicForm.amountExcludingTax
                                                }}
                                            </span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item
                                            label="原计划金额："
                                            prop="year"
                                        >
                                            <span>
                                                {{ basicForm.amount }}
                                            </span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item
                                            label="税率%："
                                            prop="taxRate"
                                        >
                                        <span>
                                            {{
                                                basicForm.taxRate
                                            }}
                                        </span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item
                                            label="税额："
                                            prop="taxAmount"
                                        >
                                          <span>
                                            {{
                                               basicForm.taxAmount
                                            }}
                                        </span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item
                                            label="变更后计划金额（元）："
                                        >
                                            <span>
                                                {{ basicForm.amountChanged }}
                                            </span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="填报人：">
                                            <span>{{
                                                basicForm.preparer
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item
                                            label="币种："
                                            prop="currency"
                                        >
                                            <span>{{
                                                basicForm.currency
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="状态：">
                                            <span>{{
                                                statusLable(basicForm.state)
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="变更后期数：">
                                            <span>{{ basicForm.period }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12"> </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="24">
                                        <el-form-item label="备注：">
                                            <span>
                                                {{
                                                    basicForm.remarks
                                                }}
                                            </span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="本位币：">
                                            <span>{{
                                                basicForm.baseCurName
                                            }}</span>
                                        </el-form-item>
                                    </el-col>

                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="人民币汇率：">
                                            <span>{{ basicForm.rmbRate }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12"> </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="本位币汇率：">
                                            <span>{{
                                                basicForm.baseCurRate
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12"> </el-col>
                                </el-row>
                                <el-row v-if="basicForm.state === 5">
                                        <el-col :span="12">
                                        <el-form-item label="作废人：">
                                            <span>{{ basicForm.nullifyCreator }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="作废原因：">
                                            <span>{{basicForm.nullifyReason }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row v-if="basicForm.state === 5">
                                    <el-col :span="12">
                                        <el-form-item label="作废说明：">
                                            <span>{{
                                                basicForm.nullifyDescription
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                        <el-col :span="12">
                                        <el-form-item label="作废时间：">
                                            <span>{{
                                                basicForm.nullifyCreated
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-form>
                        </div>
                    </div>
                    <!-- 物资明细 -->
                    <div id="detailedCon" class="con">
                        <div class="tabs-title" id="detailed">物资明细</div>
                        <div class="e-table">

                            <!-- 普通采购 -->
                            <el-table
                                v-if="!isConcentrate"
                                :data="detailedTableData"
                                border
                                style="width: 100%"
                                :row-class-name="tableRowClass"
                                :header-cell-style="{ textAlign: 'center' }"
                                :cell-style="{ textAlign: 'center' }"
                                :tree-props="{
                                    children: 'children',
                                    hasChildren: 'hasChildren'
                                }"
                                ref="multipleTable"
                                row-key="uuid"
                                key="normal"
                                default-expand-all
                                 v-sortTable="{ 'tableData': detailedTableData, '_this': this, 'ref': 'multipleTable' }"
                            >
                                <el-table-column
                                    label="操作"
                                    fixed
                                    width="100px"
                                    align="left"
                                    v-if="isBatch"
                                >

                                </el-table-column>
                                <el-table-column
                                    prop="materialClassName"
                                    label="类别"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="materialName"
                                    label="物资名称"
                                >
                                </el-table-column>
                                <el-table-column prop="spec" label="规格">
                                </el-table-column>
                                <el-table-column prop="unit" label="计量单位">
                                </el-table-column>
                                <el-table-column prop="texture" label="材质">
                                </el-table-column>
                                <el-table-column
                                    prop="demandQuantity"
                                    label="原需求数量"
                                    width="120"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="deployableQuantity"
                                    label="原可调配数"
                                    width="120"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="leaseQuantity"
                                    label="原建议租赁数"
                                    width="120"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="purchaseQuantity"
                                    label="原建采购数"
                                    width="120"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="purchasePrice"
                                    label="原采购单价（元）"
                                    width="150"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="leasePrice"
                                    label="原租赁单价（元）"
                                    width="150"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="amount"
                                    label="原金额（元）"
                                    width="120"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="timeUnit"
                                    label="原计时单位"
                                    width="120"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="estimatedTime"
                                    label="原预计使用时间"
                                    width="120"
                                >
                                </el-table-column>
                                <el-table-column prop="" width="100">
                                    <template slot="header">
                                        <div class="tab-header">
                                            需求数量<span class="tab-heade-icon"
                                                >变</span
                                            >
                                        </div>
                                    </template>
                                    <template slot-scope="{ row,$index }">
                                        <div class="history-update-tab">
                                            <el-input
                                             v-if="$index > 0"
                                               v-enter-float2="{
                                                set: row,
                                                key: 'demandQuantityChanged'
                                            }"
                                                v-model="
                                                    row.demandQuantityChanged
                                                "
                                                @input="curStateChange(row)"
                                                @blur="
                                                    createHistory(
                                                        row,
                                                        'demandQuantityChanged'
                                                    )
                                                "
                                                clearable
                                            ></el-input>
                                            <historyUpdateTable
                                                v-if="
                                                    row.demandQuantityChangedIsUpdate ===
                                                    1
                                                "
                                                @clickIcon="
                                                    clickIcon(
                                                        row.dtlId,
                                                        'demandQuantityChanged'
                                                    )
                                                "
                                                :historyTable="historyTableData"
                                            />
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="" width="100">
                                    <template slot="header">
                                        <div class="tab-header">
                                            可调配数<span class="tab-heade-icon"
                                                >变</span
                                            >
                                        </div>
                                    </template>

                                    <template slot-scope="{ row,$index  }">
                                        <div class="history-update-tab">
                                            <el-input
                                             v-if="$index > 0"

                                                v-model.number="
                                                    row.deployableQuantityChanged
                                                "
                                                @input="curStateChange(row)"
                                                @blur="
                                                    createHistory(
                                                        row,
                                                        'deployableQuantityChanged'
                                                    )
                                                "
                                                clearable
                                            ></el-input>
                                            <historyUpdateTable
                                                v-if="
                                                    row.deployableQuantityChangedIsUpdate ===
                                                    1
                                                "
                                                @clickIcon="
                                                    clickIcon(
                                                        row.dtlId,
                                                        'deployableQuantityChanged'
                                                    )
                                                "
                                                :historyTable="historyTableData"
                                            />
                                        </div>
                                    </template>
                                </el-table-column>
                                 <el-table-column prop="" width="100">
                                    <template slot="header">
                                        <div class="tab-header">
                                            租赁单价<span class="tab-heade-icon"
                                                >变</span
                                            >
                                        </div>
                                    </template>

                                    <template slot-scope="{ row,$index  }">
                                        <div class="history-update-tab">
                                            <el-input
                                             v-if="$index > 0"

                                                v-model.number="
                                                    row.leasePriceChanged
                                                "
                                                @input="curStateChange(row)"
                                                @blur="
                                                    createHistory(
                                                        row,
                                                        'leasePriceChanged'
                                                    )
                                                "
                                                clearable
                                            ></el-input>
                                            <historyUpdateTable
                                                v-if="
                                                    row.leasePriceChangedIsUpdate ===
                                                    1
                                                "
                                                @clickIcon="
                                                    clickIcon(
                                                        row.dtlId,
                                                        'leasePriceChanged'
                                                    )
                                                "
                                                :historyTable="historyTableData"
                                            />
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="" width="100">
                                    <template slot="header">
                                        <div class="tab-header">
                                            建议租赁数<span
                                                class="tab-heade-icon"
                                                >变</span
                                            >
                                        </div>
                                    </template>
                                    <template slot-scope="{ row ,$index  }">
                                        <div class="history-update-tab">
                                            <el-input
                                             v-if="$index > 0"

                                                v-model.number="
                                                    row.leaseQuantityChanged
                                                "
                                                @input="curStateChange(row)"
                                                @blur="
                                                    createHistory(
                                                        row,
                                                        'leaseQuantityChanged'
                                                    )
                                                "
                                                clearable
                                            ></el-input>
                                            <historyUpdateTable
                                                v-if="
                                                    row.leaseQuantityChangedIsUpdate ===
                                                    1
                                                "
                                                @clickIcon="
                                                    clickIcon(
                                                        row.dtlId,
                                                        'leaseQuantityChanged'
                                                    )
                                                "
                                                :historyTable="historyTableData"
                                            />
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="" width="100">
                                    <template slot="header">
                                        <div class="tab-header">
                                            建议采购数<span
                                                class="tab-heade-icon"
                                                >变</span
                                            >
                                        </div>
                                    </template>
                                    <template slot-scope="{ row  ,$index }">
                                        <div class="history-update-tab">
                                            <el-input
                                             v-if="$index > 0"

                                                v-model.number="
                                                    row.purchaseQuantityChanged
                                                "
                                                @input="curStateChange(row)"
                                                @blur="
                                                    createHistory(
                                                        row,
                                                        'purchaseQuantityChanged'
                                                    )
                                                "
                                                 v-enter-float2="{
                                                    set: row,
                                                    key: 'purchaseQuantityChanged'
                                                }"
                                                clearable
                                            ></el-input>
                                            <historyUpdateTable
                                                v-if="
                                                    row.purchaseQuantityChangedIsUpdate ===
                                                    1
                                                "
                                                @clickIcon="
                                                    clickIcon(
                                                        row.dtlId,
                                                        'purchaseQuantityChanged'
                                                    )
                                                "
                                                :historyTable="historyTableData"
                                            />
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="" width="100">
                                    <template slot="header">
                                        <div class="tab-header">
                                            采购单价(元)<span class="tab-heade-icon"
                                                >变</span
                                            >
                                        </div>
                                    </template>
                                    <template slot-scope="{ row ,$index  }">
                                        <div class="history-update-tab">
                                            <el-input
                                             v-if="$index > 0"

                                                v-model.number="
                                                    row.purchasePriceChanged
                                                "
                                                @input="curStateChange(row)"
                                                @blur="
                                                    createHistory(
                                                        row,
                                                        'purchasePriceChanged'
                                                    )
                                                "
                                                clearable
                                            ></el-input>
                                            <historyUpdateTable
                                                v-if="
                                                    row.purchasePriceChangedIsUpdate ===
                                                    1
                                                "
                                                @clickIcon="
                                                    clickIcon(
                                                        row.dtlId,
                                                        'purchasePriceChanged'
                                                    )
                                                "
                                                :historyTable="historyTableData"
                                            />
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="" width="100">
                                    <template slot="header">
                                        <div class="tab-header">
                                            金额(元)<span class="tab-heade-icon"
                                                >变</span
                                            >
                                        </div>
                                    </template>
                                    <template slot-scope="{ row }">
                                        <span>
                                            {{ row.amountChanged }}
                                        </span>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="" width="100">
                                    <template slot="header">
                                        <div class="tab-header">
                                            计时单位<span class="tab-heade-icon"
                                                >变</span
                                            >
                                        </div>
                                    </template>
                                    <template slot-scope="{ row  ,$index }">
                                        <el-select
                                        v-if="$index > 0"
                                            v-model="row.timeUnitChanged"
                                            placeholder="请选择"
                                            @input="curStateChange(row)"
                                            @blur="numYuan(row)"
                                        >
                                            <el-option
                                                v-for="item in timeUnitList"
                                                :key="item.value"
                                                :label="item.label"
                                                :value="item.label"
                                            >
                                            </el-option>
                                        </el-select>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="" width="120">
                                    <template slot="header">
                                        <div class="tab-header">
                                            预计使用时间<span
                                                class="tab-heade-icon"
                                                >变</span
                                            >
                                        </div>
                                    </template>
                                    <template slot-scope="{ row ,$index}">
                                        <div class="history-update-tab">
                                            <el-input
                                        v-if="$index > 0"

                                                v-model.number="
                                                    row.estimatedTimeChanged
                                                "
                                                @input="curStateChange(row)"
                                                clearable
                                            ></el-input>
                                        </div>
                                    </template>
                                </el-table-column>
                            </el-table>
                            <!-- 集中采购 -->
                            <el-table
                            v-else
                              :data="detailedTableData"
                                border
                                style="width: 100%"
                                :row-class-name="tableRowClass"
                                :header-cell-style="{ textAlign: 'center' }"
                                :cell-style="{ textAlign: 'center' }"
                                :tree-props="{
                                    children: 'children',
                                    hasChildren: 'hasChildren'
                                }"
                                ref="multipleTable"
                                row-key="uuid"
                                default-expand-all
                                 v-sortTable="{ 'tableData': detailedTableData, '_this': this, 'ref': 'multipleTable' }"
                            >
                               <el-table-column
                                    label="操作"
                                    fixed
                                    width="100px"
                                    align="left"
                                >

                                    <!-- <template slot-scope="{ row, $index }">

                                        <i
                                            class="el-icon-delete"
                                            style="
                                                cursor: pointer;
                                                font-size: 20px;
                                                color: red;
                                            "
                                            :class="{
                                                'icon-delete-active-color':
                                                    MouseEnterId == row.dtlId
                                            }"
                                            @click="deleteEle(row)"
                                            v-if="$index > 0"
                                        ></i>

                                    </template> -->

                                </el-table-column>
                                <el-table-column
                                    prop="materialClassName"
                                    label="类别"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="materialName"
                                    label="物资名称"
                                >
                                </el-table-column>
                                <el-table-column prop="spec" label="规格">
                                </el-table-column>
                                <el-table-column prop="unit" label="计量单位">
                                </el-table-column>
                                <el-table-column prop="texture" label="材质">
                                </el-table-column>
                                <el-table-column
                                    prop="demandQuantity"
                                    label="原需求数量"
                                    width="120"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="purchaseQuantity"
                                    label="原建议采购数"
                                    width="120"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="purchasePrice"
                                    label="原采购单价"
                                    width="120"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="amount"
                                    label="原金额（元）"
                                    width="120"
                                >
                                </el-table-column>
                                <el-table-column prop="" width="100">
                                    <template slot="header">
                                        <div class="tab-header">
                                            需求数量<span class="tab-heade-icon"
                                                >变</span
                                            >
                                        </div>
                                    </template>
                                    <template slot-scope="{ row ,$index}">
                                        <div class="history-update-tab">
                                            <el-input
                                            v-if="$index>0"
                                                v-model="
                                                    row.demandQuantityChanged
                                                "
                                                @input="curStateChange(row)"
                                                @blur="
                                                    createHistory(
                                                        row,
                                                        'demandQuantityChanged'
                                                    )
                                                "
                                                v-enter-float2="{
                                                set: row,
                                                key: 'demandQuantityChanged'
                                            }"
                                                clearable
                                            ></el-input>
                                            <historyUpdateTable
                                                v-if="
                                                    row.demandQuantityChangedIsUpdate ===
                                                    1
                                                "
                                                @clickIcon="
                                                    clickIcon(
                                                        row.dtlId,
                                                        'demandQuantityChanged'
                                                    )
                                                "
                                                :historyTable="historyTableData"
                                            />
                                        </div>
                                    </template>
                                </el-table-column>

                                <el-table-column prop="" width="100">
                                    <template slot="header">
                                        <div class="tab-header">
                                            建议采购数<span
                                                class="tab-heade-icon"
                                                >变</span
                                            >
                                        </div>
                                    </template>
                                    <template slot-scope="{ row,$index }">
                                        <div class="history-update-tab">
                                            <el-input
                                            v-if="$index > 0"
                                                v-model="
                                                    row.purchaseQuantityChanged
                                                "
                                                @input="curStateChange(row)"
                                                @blur="
                                                    createHistory(
                                                        row,
                                                        'purchaseQuantityChanged'
                                                    )
                                                "
                                                clearable
                                                 v-enter-float2="{
                                                    set: row,
                                                    key: 'purchaseQuantityChanged'
                                                }"
                                            ></el-input>
                                            <historyUpdateTable
                                                v-if="
                                                    row.purchaseQuantityChangedIsUpdate ===
                                                    1
                                                "
                                                @clickIcon="
                                                    clickIcon(
                                                        row.dtlId,
                                                        'purchaseQuantityChanged'
                                                    )
                                                "
                                                :historyTable="historyTableData"
                                            />
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="" width="100">
                                    <template slot="header">
                                        <div class="tab-header">
                                            采购单价<span class="tab-heade-icon"
                                                >变</span
                                            >
                                        </div>
                                    </template>
                                    <template slot-scope="{ row,$index }">
                                        <div class="history-update-tab">
                                            <el-input
                                                 v-if="$index>0"
                                                v-model.number="
                                                    row.purchasePriceChanged
                                                "
                                                @input="curStateChange(row)"
                                                @blur="
                                                    createHistory(
                                                        row,
                                                        'purchasePriceChanged'
                                                    )
                                                "
                                                v-enter-float="{
                                                set: row,
                                                key: 'purchasePriceChanged'
                                            }"
                                                clearable
                                            ></el-input>
                                            <historyUpdateTable
                                                v-if="
                                                    row.purchasePriceChangedIsUpdate ===
                                                    1
                                                "
                                                @clickIcon="
                                                    clickIcon(
                                                        row.dtlId,
                                                        'purchasePriceChanged'
                                                    )
                                                "
                                                :historyTable="historyTableData"
                                            />
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="" width="100">
                                    <template slot="header">
                                        <div class="tab-header">
                                            金额<span class="tab-heade-icon"
                                                >变</span
                                            >
                                        </div>
                                    </template>
                                    <template slot-scope="{ row }">
                                        <span>
                                            {{ row.amountChanged }}
                                        </span>
                                    </template>
                                </el-table-column>
                            </el-table>
                            <div class="errorMsg" v-if="errorMsg.length > 0">
                                <span
                                    v-for="(item, index) in errorMsg"
                                    :key="index"
                                >
                                    {{ item }}
                                </span>
                            </div>
                        </div>
                    </div>
                    <!-- 附件信息 -->
                    <div id="attachCon" class="con">
                        <div class="tabs-title" id="attach">附件信息</div>
                        <attach-comp
                            :relationId="attachId"
                            bucketName="turnover"
                            isView
                        />
                    </div>
                    <!-- 审核历史 -->
                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <div class="e-table">
                            <ComAuditHistoryIndex
                                :billType="6086"
                                ref="AuditHistoryRef"
                            />
                        </div>
                    </div>
                </div>
            </el-tabs>
        </div>
       <div class="buttons">
       <ComExaButtons
                :auditState="auditState"
                :state="basicForm.state"
                @exas="exas"
                :founderId="basicForm.founderId"
            />
            <el-button size="small" @click="handleClose">取消</el-button>
        </div>
        <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
    </div>
</template>

<script>
import AttachComp from '@/components/common/attachIndex'
import ComAuditHistoryIndex from '@/pages/revolveMaterialManage/components/auditHistory/auditHistoryIndex'
import auditRequest from '@/api/turnover/audit.js'
import planRequest from '@/api/turnover/plan.js'
import historyUpdateTable from '@/components/common/historyUpdateTable'
import { openAppClient, getUuid } from '@/utils/common'
import ComExaButtons from '@/components/common/exaButtons'
import { exas } from '@/pages/revolveMaterialManage/common/revolveCom.js'
import { mapMutations, mapState } from 'vuex'
import $ from 'jquery'
import '@/utils/jquery.scrollTo.min'
export default {
    components: {
        AttachComp,
        ComAuditHistoryIndex,
        historyUpdateTable,
        ComExaButtons
    },
    computed: {
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        },
        attachId () {
            return this.id
        },
        //是否集中采购
        isConcentrate () {
            if (
                this.basicForm.purchaseType &&
                this.basicForm.purchaseType == 1
            ) {
                return true
            } else {
                return false
            }
        },
        ...mapState({
            userInfo: state => state.userInfo,
            timeUnitList: state => state.equip.equipData.timeUnitList //计时单位
        }),
        statusLable () {
            return param => {
                const state = this.$store.state.equip.equipData.state
                const obj = state.find(x => x.value === param)
                if (obj !== undefined) {
                    return obj.label
                }
            }
        }
    },
    mounted () {
        this.getLastConHeight()
        // 保存所有tabName
        const arr = ['baseInfo', 'detailed', 'attach', 'auditHistory']

        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const itemTop = document.getElementById(item).offsetTop
                    return itemTop
                })
            }
            const scrollTop =
                document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if (scrollTop + 1 >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })
    },
    created () {
        this.id = this.$route.query.billid
        this.getCurrentUnitInfo()
        this.getDtlList()

        this.getBasicInfo()
        this.getUserInfo()
    },
    data () {
        return {
            tabsName: 'baseInfo',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            basicForm: {
                amount: 0,
                amountChanged: 0,
                amountExcludingTax: 0,
                annualDemandPlanBillId: '',
                annualDemandPlanBillNo: '',
                billId: '',
                billNo: '',
                currency: '',
                currencyId: '',
                nullifyCreated: '',
                nullifyCreator: '',
                nullifyCreatorId: '',
                nullifyDescription: '',
                nullifyReason: '',
                orgId: '',
                orgName: '',
                period: 0,
                planDate: '',
                preparer: '',
                preparerId: '',
                purchaseType: 0,
                remarks: '',
                rmbRate: 0,
                state: '',
                taxAmount: 0,
                taxRate: 0,
                workId: '',
                year: ''
            },
            isBatch: true,
            formLabelWidth: '180px',
            detailedTableData: [
                // {
                //     amount: 0,
                //     billId: '',
                //     demandQuantity: 0,
                //     deployableQuantity: 0,
                //     dtlId: '',
                //     endTime: '',
                //     leaseQuantity: 0,
                //     materialClassId: '',
                //     materialClassName: '',
                //     materialId: '',
                //     materialName: '',
                //     price: 0,
                //     purchaseQuantity: 0,
                //     spec: '',
                //     startTime: '',
                //     texture: '',
                //     unit: ''
                // }
            ], //物资明细
            tableData: [],
            basicInfo: {},
            stateArr: ['草稿', '审核中', '已审核', '已作废'],
            currencyArr: [], //币种列表
            auditState: {},
            auditParams: {
                billId: this.$route.query.billid,
                billType: 6086,
                freeNextUnitIndex: 0,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: ''
            },
            nullifyParams: { //作废
                'billId': this.$route.query.billid,
                'billType': 6086,
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': ''
            },
            rules: {
                taxRate: [
                    { required: true, message: '请填写税率', trigger: 'blur' }
                ],
                taxAmount: [
                    { required: true, message: '请填写税额', trigger: 'blur' }
                ]
            },
            multipleSelection: [],
            curRow: {},
            timeUnitChanged: ['台班', '月', '日'],
            createHistoryData: [],
            isErrorMsg: true, //是否提醒错误信息
            errorMsg: [],
            tabArr: []
        }
    },
    methods: {
        ...mapMutations(['setAuditParams', 'setHistoryTableData']),

        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('recodesCon')) {
                    const lastConHeight =
                        document.getElementById('recodesCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        getBasicInfo () {
            this.$Ajax
                .httpGet({
                    url: '/turnover/annualDemandPlanChanged/findById',
                    params: {
                        billId: this.id
                    },
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                .then(res => {
                    let arr = this.basicForm.dtls
                    for (let key in res) {
                        this.basicForm[key] = res[key]
                        this.basicForm.dtls = arr
                    }
                })
        },
        //获取本地登录信息
        getUserInfo () {
            const userInfo = JSON.parse(window.localStorage.getItem('vuex'))
                .userInfo.orgInfo
            this.basicForm.orgId = userInfo.orgId
            this.basicForm.orgName = userInfo.orgName
        },

        //选择币种的事件
        changeCurrency () {
            const obj = this.currencyArr.find(
                item => item.kvKey === this.basicForm.currency
            )
            this.basicForm.currencyId = obj.kvId
        },
        getDicValue () {
            this.$store.dispatch('equip/setTimeUnitList')
        },

        getCurrentUnitInfo () {
            auditRequest.getCurrentUnitInfo(this.auditParams).then(res => {
                this.auditState = res
            })
        },
        onSave () {
            this.getBasicInfo()
            this.getDtlList()
        },
        submit () {
            this.detailedTableData.forEach(item => {
                item.billId = this.id
            })

            this.$refs.ruleForm.validate(val => {
                if (val) {
                    // 明细非空验证
                    this.verifyTable()
                    if (this.isErrorMsg) {
                        return
                    }
                    let promise1 =
                        planRequest.turnoverAnnualDemandPlanChangedUpdate(
                            this.basicForm
                        )
                    let promise2 =
                        planRequest.turnoverAnnualDemandPlanChangedUpdateDtlLsit(
                            this.detailedTableData
                        )
                    Promise.all([promise1, promise2]).then(() => {
                        this.clientPop('suc', '保存成功', this.onSave)
                    })
                }
            })
        },
        submitCommit () {

            this.detailedTableData.forEach(item => {
                item.billId = this.id
            })

            this.$refs.ruleForm.validate(val => {
                if (val) {
                    // 明细非空验证
                    this.verifyTable()
                    if (this.isErrorMsg) {
                        return
                    }
                    let promise1 =
                        planRequest.turnoverAnnualDemandPlanChangedUpdate(
                            this.basicForm
                        )
                    let promise2 =
                        planRequest.turnoverAnnualDemandPlanChangedUpdateDtlLsit(
                            this.detailedTableData
                        )
                    Promise.all([promise1, promise2]).then(() => {
                        auditRequest.commit(this.auditParams).then(()=>{

                            this.clientPop('suc', '保存并提交成功', this.handleClose)
                        })
                    })
                }
            })

        },
        audit () {
            // 新增历史修改
            if (this.createHistoryData.length > 0) {
                console.log(this.createHistoryData)
                planRequest
                    .turnoverAnnualDemandPlanCreateHistory(
                        this.createHistoryData,
                        this.auditParams.billType
                    )
                    .then(() => {
                        this.getDtlList()
                    })
            }

            this.setAuditParams(this.auditParams)
            // 客户端弹窗弹出本地页面
            openAppClient('/exaDialog', '填写审核意见', () => {
                const auditParams = JSON.parse(localStorage.vuex).auditParams
                auditRequest.audit(auditParams).then(() => {
                    this.clientPop('suc', '审核成功')
                    this.getCurrentUnitInfo()
                    this.getAuditHistory()
                })
            })
        },
        //更新基本信息
        updateBaseInfo () {
            this.basicForm.isSignContract
                ? (this.basicForm.isSignContract = 1)
                : (this.basicForm.isSignContract = 0)
            return new Promise((resolve, reject) => {
                this.$refs.ruleForm.validate(valid => {
                    if (valid) {
                        planRequest
                            .turnoverAnnualDemandPlanChangedUpdate(this.basicForm)
                            .then(() => {
                                this.getBasicInfo() //更新基本信息
                                resolve()
                            })
                            .catch(err => {
                                this.setError('baseInfo')
                                reject(err)
                            })
                    } else {
                        this.setError('baseInfo')
                        this.scorllError()
                        return false
                    }
                })
            })
        },
        //更新计划明细
        updateBudgetDtl () {

            this.detailedTableData.forEach(item => {
                item.billId = this.id
            })
            return new Promise((resolve, reject) => {
                this.verifyTable()
                    .then(() => {
                        planRequest
                            .turnoverAnnualDemandPlanChangedUpdateDtlLsit(this.detailedTableData)
                            .then(() => {
                                this.getDtlList() //更新明细
                                resolve()
                            })
                            .catch(err => {
                                this.setError('detailed')
                                reject(err)
                            })
                    })
                    .catch(err => {
                        this.setError('detailed')
                        reject(err)
                    })
            })
        },
        //刷新历史审核列表
        getAuditHistory () {
            this.$refs.AuditHistoryRef.auditHistory()
        },

        //点击删除
        clickDel () {
            this.clientPop(
                'info',
                '确定要删除吗？删除的数据可以在【回收站】还原或彻底删除。',
                this.delData
            )
        },
        delData () {
            this.$Ajax
                .httpGet({
                    url: '/turnover/annualDemandPlanChanged/delete',
                    params: { billId: this.id },
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                .then(() => {
                    this.clientPop('suc', '删除成功', this.handleClose)
                })
        },

        handleClose () {
            this.$router.replace('/yearNeedPlan')
        },
        /**明细 */
        //获取原单明细
        getDtlList () {
            planRequest
                .turnoverAnnualDemandPlanChangedFindByBillId(this.id)
                .then(res => {
                    if (res.length > 0) {
                        res.forEach(item => {
                            item.materialClassName = item.topClassName
                            item.type = this.basicForm.purchaseType + 1
                            item.uuid = getUuid()
                            item.children.forEach(i => {
                                i.uuid = i.dtlId
                            })
                            const count = item.children.reduce(
                                (prev, c) => (prev += c.amount || 0),
                                0
                            )
                            item.materialName = `小计： ${count}`
                        })

                        this.detailedTableData = res
                        //明细金额向上汇总到基础表单 不含税计划金额（元）
                        this.collectCount()
                        this.onTaxRate()
                    }
                })
        },

        /**
         * 下边几个按钮
         */

        // 审核相关操作
        async exas (arg) {
            const requestFn = ()=>{
                return [
                    this.updateBaseInfo(),
                    this.updateBudgetDtl(),
                ]
            }
            exas(arg, this, requestFn)
        },
        //判断当前状态是否已修改
        curStateChange (row) {
            // row.amount =  row.demandQuantity * row.purchasePrice
            if(row.oldState != -1) {
                if(row.annualDemandPlanDtlId === '' || row.annualDemandPlanDtlId === null || !row.annualDemandPlanDtlId) {
                    this.currentRow.changeType = 1
                    this.currentRow.oldState = 1
                }else{
                    this.currentRow.changeType = 2
                    this.currentRow.oldState = 2
                }
                this.numYuan(row)
            }
        },
        numYuan (row) {
            //判断是否为空

            if (this.isConcentrate) {
                //集采汇总
                if (row.purchaseQuantityChanged && row.purchasePriceChanged) {
                    row.amountChanged =
                        Number(row.purchaseQuantityChanged * row.purchasePriceChanged).toFixed(2)
                    this.collectCount()
                    this.onTaxRate()
                }
            } else {
                if(row.leaseQuantityChanged &&
          row.leasePriceChanged &&
          row.estimatedTimeChanged &&
          row.purchaseQuantityChanged &&
          row.purchasePriceChanged &&
          row.deployableQuantityChanged) {
                    //普通汇总
                    row.amountChanged =
                       Number(row.leaseQuantityChanged *
                            row.leasePriceChanged *
                            row.estimatedTimeChanged +
                        row.purchaseQuantityChanged * row.purchasePriceChanged +
                        row.deployableQuantityChanged *
                            row.purchasePriceChanged).toFixed(2)
                    this.collectCount()
                    this.onTaxRate()
                }

            }

        },

        //明细金额向上汇总到基础表单 不含税计划金额（元）
        collectCount () {
            this.basicForm.amountExcludingTax = 0
            this.detailedTableData.forEach(v => {
                v.children.forEach(item => {
                    if (item.oldState != -1) {
                        this.basicForm.amountExcludingTax += Number(item.amountChanged)
                    }
                })
                const count = v.children.reduce(
                    (prev, c) => (prev += Number(c.amountChanged) || 0),
                    0
                )
                v.materialName = `小计： ${count}`
            })
        },
        //删除逻辑
        handleSelectionChange (val) {
            this.multipleSelection = val
        },
        // 明细批量删除
        detilDel () {
            this.existDelBeforeList() //保存删除之前的计划明细状态
            let length = this.errorMsg.length

            if (this.multipleSelection.length > 0) {
                this.multipleSelection.forEach(item => {
                    if (item.dtlId) {
                        if (item.dtlId) {
                            item.changeType = -1
                            item.state = -1
                            this.collectCount() //重新向上汇总
                            this.onTaxRate()
                            if (length > 0) {
                                this.verifyTable()
                            }
                            this.$refs.multipleTable.clearSelection()
                        }
                    } else {
                        const localArr = []
                        localArr.push(item)
                        for (
                            let i = this.detailedTableData.length;
                            i > 0;
                            i--
                        ) {
                            for (let j = 0; j < localArr.length; j++) {
                                if (
                                    this.detailedTableData[i - 1] ===
                                    localArr[j]
                                ) {
                                    this.detailedTableData.splice(i - 1, 1)
                                    this.collectCount()
                                    this.onTaxRate()
                                    if (length > 0) {
                                        this.verifyTable()
                                    }
                                }
                            }
                        }
                        this.$refs.multipleTable.clearSelection()
                    }
                })
            }
        },
        //单个删除计划明细
        handleDelete (row, $index) {
            row.oldState = row.changeType //存删除之前的状态
            let length = this.errorMsg.length
            if (row.isQuote === 1 || row.isQuote === 1) {
                this.clientPop(
                    'info',
                    '该数据已经被其他单据引用或者已汇总，不能删除！'
                )
            } else {
                if (row.dtlId) {
                    this.$set(this.detailedTableData[$index], 'changeType', -1)
                    this.$set(this.detailedTableData[$index], 'state', -1)
                    if (length > 0) {
                        this.verifyTable()
                    }
                    this.collectCount() //重新向上汇总
                    this.onTaxRate()
                } else {
                    this.detailedTableData.splice($index, 1)
                    this.collectCount() //重新向上汇总
                    this.onTaxRate()
                    if (length > 0) {
                        this.verifyTable()
                    }
                }
            }
        },
        //取消删除
        cancelDelete () {
            const length = this.multipleSelection.length
            if (length === 0) {
                this.clientPop('info', '你还未选择删除的数据,请选择!')
            } else {
                this.multipleSelection.forEach(item => {
                    if (item.changeType === -1) {
                        let obj = this.detailedTableData.find(
                            x => x.dtlId === item.dtlId
                        )
                        obj.state = obj.oldState
                        obj.changeType = obj.oldState
                    }
                })
                this.collectCount() //重新向上汇总
                this.onTaxRate()
                this.$refs.multipleTable.clearSelection()
            }
        },
        //存删除之前的计划明细的状态
        existDelBeforeList () {
            this.multipleSelection.forEach(item => {
                let obj = this.detailedTableData.find(
                    v => v.dtlId === item.dtlId
                )
                obj.oldState = obj.state
            })
        },
        tableRowClass ({ row }) {
            if (row.oldState == -1) {
                return 'red'
            } else if (row.oldState == 1) {
                return 'green'
            } else if (row.oldState == 2) {
                return 'yellow'
            } else if (row.children) {
                return 'warning-row'
            }
            return ''
        },
        // 编辑的时候造历史修改数据结构
        createHistory (row, e) {
            if (row.dtlId) {
                this.createHistoryData.push({
                    historyId: '',
                    modifedName: '',
                    modifiedDate: '',
                    modifiedId: '',
                    opinion: '',
                    sourceId: row.dtlId,
                    sourceValue: 0,
                    updateColumn: e, //修改字段
                    updatedValue: row[e] //修改后的值
                })
            }
            this.numYuan(row)
        },
        //税率失去焦点的时候 计算 税额 = 不含税计划金额（元）*税率%
        onTaxRate () {
            if (
                this.basicForm.amountExcludingTax != 0 &&
                this.basicForm.taxRate != 0
            ) {
                this.basicForm.taxAmount =
                    (this.basicForm.amountExcludingTax *
                        this.basicForm.taxRate) /
                    100

                this.basicForm.amountChanged =
                    this.basicForm.taxAmount +
                    this.basicForm.amountExcludingTax
            }
        },
        //点击图标的时候 获取历史记录
        clickIcon (dtlId, column) {
            this.setHistoryTableData([])
            planRequest
                .turnoverAnnualDemandPlanGetHistoryList(
                    dtlId,
                    column,
                    this.auditParams.billType
                )
                .then(res => {
                    this.historyTableData = res
                    this.setHistoryTableData(res)
                })
        },
        //计划明细非空验证
        verifyTable () {
            return new Promise((resolve, reject) => {

                this.errorMsg = []
                this.detailedTableData.forEach(v => {
                    v.children.forEach((item, index)=>{
                        if (item.changeType !== -1 && item.oldState !== -1) {
                            if (item.demandQuantityChanged === null || item.demandQuantityChanged === '') {
                                let str = `请填写第 ${index + 1} 行的变更需求数量`
                                this.errorMsg.push(str)
                            }

                            if (item.purchaseQuantityChanged === null || item.purchaseQuantityChanged === '') {
                                let str = `请填写第 ${index + 1} 行的变更建议采购数`
                                this.errorMsg.push(str)
                            }
                            if (item.purchasePriceChanged === null || item.purchasePriceChanged === '') {
                                let str = `请填写第 ${index + 1} 行的变更单价(元)`
                                this.errorMsg.push(str)
                            }

                            if (!this.isConcentrate) {
                                if (item.timeUnitChanged === null || item.timeUnitChanged === '') {
                                    let str = `请填写第 ${index + 1} 行的变更计时单位`
                                    this.errorMsg.push(str)
                                }
                                if (item.estimatedTimeChanged === null || item.estimatedTimeChanged === '') {
                                    let str = `请填写第 ${
                                index + 1
                            } 行的变更预计使用时间`
                                    this.errorMsg.push(str)
                                }
                                if (item.deployableQuantityChanged === null || item.deployableQuantityChanged === '') {
                                    let str = `请填写第 ${index + 1} 行的变更可调配数`
                                    this.errorMsg.push(str)
                                }
                                if (item.leasePriceChanged === null || item.leasePriceChanged === '') {
                                    let str = `请填写第 ${index + 1} 行的租赁单价变更`
                                    this.errorMsg.push(str)
                                }
                            }
                        }
                    })

                })
                if (this.errorMsg.length > 0) {
                    this.isErrorMsg = true

                    reject()

                } else {
                    resolve()

                    this.isErrorMsg = false
                }

            })

        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item => {
                let index = this.tabArr.findIndex(x => x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
        //设置错误标签
        setError (name) {
            if (!this.errorList.find(x => x === name)) {
                this.errorList.push(name)
            }
        },
        //点击删除的时候
        deleteEle (row) {
            row.changeType = -1
            row.oldState = -1
        }
    }
}
</script>

<style lang="scss" scoped>
::v-deep.el-table .warning-row {
    .el-checkbox {
        display: none;
    }
}
.e-table {
    min-height: auto;
    background: #fff;
}
.upload {
    margin: 20px auto;
    display: flex;
    justify-content: center;
    text-align: center;
}

.upload-demo {
    display: flex;
    justify-content: center;
    align-items: center;
}

::v-deep.el-input--suffix .el-input__inner {
    padding-right: 5px;
}
::v-deep.el-table .cell {
    text-align: center;
}
</style>
